<?php
namespace mobadmin\action;

use api\utils\SaasApiClient;
use api\utils\WeiXinApi;
use herosphp\bean\Beans;
use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Workerman\Protocols\Http;

/**
 * 认证中心 index 控制器
 */
class AuthAction extends CommonAction {

    public $manager;
    public function __construct()
    {
        parent::__construct();
        $this -> manager = Beans::get("mobadmin.manager.service");
    }

    /**
     * 首页方法
     * @param HttpRequest $request
     */
    public function index(HttpRequest $request) {

        //获取当前用户的的saas验证信息
        $info = $this -> manager->getLoginManager();
        if( $info['username'] ){
            $this -> assign('username',$info['username']);
        }
        $token = md5(time().json_encode($info));
        $this -> manager -> setSession('token',$token);
        $this -> assign('token',$token);
        $this -> assign('title',"手机认证");
        $this->setView("auth");

    }

    /**
     * 提交到此方法进行验证
     * @param HttpRequest $request
     */
    public function do_auth(HttpRequest $request){
        $params = $request -> getParameters();
        $token = $params['token'];
        $code = $params['vcode'];
        $username = $params['mobile'];
        $code2 = $this->manager->getSession('vcode');
        if( $username.$code != $code2 ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"验证码错误");
        }
        $token2 = $this->manager->getSession('token');
        if( $token == $token2 ){
            $this->manager->setSession('token',md5(time()));
        }else{
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"页面已失效,请刷新后再试！");
        }
        $password = rand(100000,999999);
        $info = $this -> manager -> getLoginManager();
        $wx_id = $info['wxId'];
        $url = "api/user/authUser";
        $params = array(
            'username'=>$username,
            'password'=>md5($password),
            'wx_id' => $wx_id
        );
        $result = SaasApiClient::send($url,$params);
        if( $result -> isSucess() ){
            //插入到offer的manager表，如果已经有记录的话，就更新；虽然我不是很赞同这样做
            $managerData['saas_user_id'] = $result->getData();
            $managerData['username']=$username;
            $managerData['password']=md5(md5($password));
            $managerData['name']='offer_'.substr($managerData['username'],4);;
            $managerData['status']= 1;
            $managerData['addtime']= date('Y-m-d H:i:s');
            $managerData['updatetime']= date('Y-m-d H:i:s');

            if(!$this -> manager -> replace($managerData)){
                AjaxResult::ajaxFailtureResult();
            }
            $this -> manager -> setSession("username",$username);
            $site_url = getConfig('site_url');
            $contents = "恭喜您，该手机号码验证成功！您PC端的登录帐号为：{$username},密码为：{$password}；您可以登录网址 {$site_url} 修改密码和查看所有报价信息，祝您生活愉快，感谢您的支持！";
            $res = $this -> getSMS($contents,$username);
            if($res){
                Log::info("发送密码给客户成功，用户名：{$username} 初始密码：".$password);
            }else{
                Log::info("发送密码给客户失败，用户名：{$username} 初始密码：".$password);
            }
            AjaxResult::ajaxSuccessResult();
        }else{
            Log::error("用户名：{$username}认证失败，接口返回：".$result->getMessage());
            AjaxResult::ajaxFailtureResult();
        }

    }

    /**
     * 获取验证码，先去校验手机号码是否被注册
     * @param HttpRequest $request
     */
    public function getCode(HttpRequest $request){

        $mobile = $request->getParameter('mobile','trim');
        //校验手机号码是否被绑定
        $uri = "api/user/count";
        $params = array(
            'conditions'=>array(
                'username'=>$mobile
            )
        );
        $result = SaasApiClient::send($uri,$params);
        if( $result -> isSucess() ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"该手机号已经被绑定！",null);
        }
        $code = rand(1000,9999);
        $this -> manager -> setSession('vcode',$mobile.$code);
        $contents = "验证码{$code}，请勿泄露给他人，验证码有效时长5分钟！";
        $res = $this -> getSMS($contents,$mobile);
        if($res){
            Log::info("{$mobile}发送成功，验证码：".$code);
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"发送成功",null);
        }else{
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败",null);
        }
    }

    /**
     * 获取短信
     * @param $contents
     * @param $mobile
     * @return bool
     */
    protected function getSMS($contents,$mobile){
        $service = Beans::get('sms.sms.service');
        return $service -> send($contents, $mobile);

    }

}
